package com.gimi.cloud.jimi.client.service.home.impl;

import com.gimi.cloud.jimi.client.service.home.HomePageService;
import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.enums.common.RedisKeyEnum;
import com.gimi.cloud.jimi.common.exception.MsgException;
import com.gimi.cloud.jimi.common.utils.JsonUtil;
import com.gimi.cloud.jimi.common.utils.StringUtil;
import com.gimi.cloud.jimi.common.utils.oss.AliOSSUtil;
import com.gimi.cloud.jimi.common.utils.reqhead.Response;
import com.gimi.cloud.jimi.commonService.common.JmConfigService;
import com.gimi.cloud.jimi.dao.dao.homePage.AdDao;
import com.gimi.cloud.jimi.dao.dao.homePage.ColumnDao;
import com.gimi.cloud.jimi.dao.dao.homePage.ColumnProdDao;
import com.gimi.cloud.jimi.dao.dao.homePage.MajorAdDao;
import com.gimi.cloud.jimi.dao.dao.product.ProductDao;
import com.gimi.cloud.jimi.dao.dao.product.ProductStatusDao;
import com.gimi.cloud.jimi.dao.redis.IRedisService;
import com.gimi.cloud.jimi.dto.app.AdDTO;
import com.gimi.cloud.jimi.dto.app.ColumnDTO;
import com.gimi.cloud.jimi.dto.app.ColumnProdDTO;
import com.gimi.cloud.jimi.dto.app.MajorAdDTO;
import com.gimi.cloud.jimi.dto.product.ProductDto;
import com.gimi.cloud.jimi.dto.product.ProductStatusDTO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Created by shazhiwei on 2017/12/27.
 */
@Service
public class HomePageServiceImpl implements HomePageService{
    private final ColumnDao columnDao;
    private final AdDao adDao;
    private final IRedisService redisService;
    private final MajorAdDao majorAdDao;
    private final ColumnProdDao columnProdDao;
    private final ProductDao productDao;
    private final JmConfigService jmConfigService;
    private final ProductStatusDao productStatusDao;
    private static Logger logger = LoggerFactory.getLogger(HomePageServiceImpl.class);

    public HomePageServiceImpl(ColumnDao columnDao,AdDao adDao,IRedisService redisService,
                               MajorAdDao majorAdDao,ColumnProdDao columnProdDao,ProductDao productDao,
                               JmConfigService jmConfigService,ProductStatusDao productStatusDao){
        this.columnDao = columnDao;
        this.adDao = adDao;
        this.redisService = redisService;
        this.majorAdDao = majorAdDao;
        this.columnProdDao = columnProdDao;
        this.productDao = productDao;
        this.jmConfigService = jmConfigService;
        this.productStatusDao = productStatusDao;
    }

    @Override
    public String homePageColumnList() {
        Integer pageId = getPageId();
        String redisKey = RedisKeyEnum.APP_HOME_PAGE_COLUMN_AD_LIST.getKey() + "page" + pageId;
        //从redis获取数据
        String columns = getColumnListFromRedis(redisKey);
        if(!StringUtil.isBlank(columns)){
            logger.info("===>从redis获取数据成功");
            return columns;
        }
        //从mysql获取首页数据
        synchronized (this){
            columns = getColumnListFromRedis(redisKey);
            if(StringUtil.isBlank(columns)){
                columns = getColumnListFromMysql(redisKey,pageId);
            }
        }

        if(StringUtil.isBlank(columns)){
            logger.error("===>获取数据失败");
        }
        return columns;
    }

    @Override
    public String homePageMajorAdList() {
        Integer pageId = getPageId();
        String redisKey = RedisKeyEnum.APP_HOME_PAGE_MAJOR_AD_LIST.getKey() + "page" + pageId;
        //从redis获取数据
        String ads = getMajorAdListFromRedis(redisKey);
        if(!StringUtil.isBlank(ads)){
            return ads;
        }
        //从mysql获取首页数据
        synchronized (this){
            ads = getMajorAdListFromRedis(redisKey);
            if(StringUtil.isBlank(ads)){
                ads = getMajorAdListFromMysql(redisKey,pageId);
            }
        }
        return ads;
    }

    @Override
    public List<ColumnDTO> columnList(Integer pageId) {
        return columnDao.columnList(pageId);
    }

    @Override
    public List<AdDTO> adList(String columnIds) {
        if(StringUtil.isBlank(columnIds)){
            return null;
        }
        List<AdDTO> result = adDao.getListByColumnIds(columnIds);
        if(result != null) {
            Date imgDate = new Date();
            for (AdDTO ad : result) {
                ad.setImgUrl(AliOSSUtil.getFileUrl(ad.getImgUrl(), AliOSSUtil.getNoEffictDateByDay(1)));
            }
        }
        return result;
    }

    /**
     * 从redis获取栏目
     */
    private String getColumnListFromRedis(String redisKey){
        //从redis获取首页数据
        String result = "";
        try{
            result = redisService.get(redisKey);
        }catch (Exception e){
            logger.error("===>从redis获取数据异常");
        }
        return result;
    }

    /**
     * 从mysql获取栏目
     */
    private String getColumnListFromMysql(String redisKey,Integer pageId){
        String result = "";
        Response response = new Response();
        //查询可用栏目,获得栏目columnIds
        List<ColumnDTO> columnList = columnList(pageId);
        String columnIds = getColumnIds(columnList);
        if(columnIds.length() < 1){
            throw new MsgException(ResponseCodeEnum.APP_COLUMN_ID_NULL);
        }
        logger.info("===>获取栏目ids: " + columnIds);
        //根据columnIds查询广告列表
        List<AdDTO> adList = adList(columnIds);
        if(adList == null || adList.size() == 0){
            throw new MsgException(ResponseCodeEnum.APP_AD_ID_NULL);
        }
        logger.info("===>栏目下广告列表size = " + adList.size());
        //将广告塞到栏目dto的广告list中
        for(ColumnDTO column : columnList){
            List<AdDTO> list = new ArrayList<>();
            for (AdDTO ad : adList){
                //String adStatus = ad.getAdStatus();
                //ad.setAdStatus(CommonEnume.AdStatus.valueOf(adStatus).getValue());//将a,b,c,d转成状态
                if(column.getColumnId() == ad.getColumnId()){
                    //ad.setImgUrl(AliOSSUtil.getFileUrl(ad.getImgUrl(), new Date()));
                    list.add(ad);
                }
            }
            column.setAdList(list);
        }

        response.setResponseCode(ResponseCodeEnum.SUCCESSED);
        response.setRes_data(columnList);
        result = JsonUtil.toJson(response);
        try {
            logger.info("===>从mysql获取数据成功");
            redisService.set(redisKey,result,2L,TimeUnit.MINUTES);//过期时间2分钟
        }catch (Exception e){
            logger.error("===>redis保存数据异常");
        }
        return result;
    }

    /**
     * 从redis获取推广列表
     */
    private String getMajorAdListFromRedis(String redisKey){
        //从redis获取首页数据
        String result = "";
        try{
            result = redisService.get(redisKey);
        }catch (Exception e){
            logger.error("===>从redis获取数据异常");
        }
        return result;
    }

    /**
     * 从mysql获取推广列表
     */
    private String getMajorAdListFromMysql(String redisKey,Integer pageId){
        Response response = new Response();
        String result = "";
        Map<String,Object> data = new HashMap<>();
        List<MajorAdDTO> majorAdList = majorAdDao.getList(pageId);
        List<MajorAdDTO> bannerList = new ArrayList<>();
        List<MajorAdDTO> normalList = new ArrayList<>();
        if(majorAdList != null && majorAdList.size() > 0){
            Date imgDate = new Date();
            for(MajorAdDTO dto : majorAdList){
                dto.setImgUrl(AliOSSUtil.getFileUrl(dto.getImgUrl(), AliOSSUtil.getNoEffictDateByDay(1)));
                if(dto.getType() == 1){
                    bannerList.add(dto);
                }else if(dto.getType() == 2){
                    normalList.add(dto);
                }
            }
        }
        data.put("bannerList",bannerList);
        data.put("majorAdList",normalList);
        response.setResponseCode(ResponseCodeEnum.SUCCESSED);
        response.setRes_data(data);
        result = JsonUtil.toJson(response);
        if(bannerList.size() > 0 && normalList.size() > 0){
            try{
                redisService.set(redisKey,result,2L,TimeUnit.MINUTES);//过期时间为2分钟
            }catch (Exception e){
                logger.error("===>保存redis异常");
            }
        }
        return result;
    }

    private String getColumnIds(List<ColumnDTO> columnList){
        StringBuilder result = new StringBuilder();
        if(columnList != null && columnList.size() > 0){
            for(ColumnDTO dto : columnList){
                result.append(dto.getColumnId()).append(",");
            }
            if(result.length() > 0){
                result.delete(result.length() -1,result.length());
            }
        }
        return result.toString();
    }

    /*private Map<String, Object> addMajorAdFromMysql(){
        List<MajorAdDTO> majorAdList = majorAdDao.getList();
        if(majorAdList != null && majorAdList.size() > 0){
            List<MajorAdDTO> bannerList = new ArrayList<>();
            List<MajorAdDTO> normalList = new ArrayList<>();
            for(MajorAdDTO dto : majorAdList){
                if(dto.getType() == 1){
                    bannerList.add(dto);
                }else if(dto.getType() == 2){
                    normalList.add(dto);
                }
            }
            result.put("bannerList",bannerList);
            result.put("adList",normalList);
        }else{
            result.put("bannerList",null);
            result.put("adList",null);
        }
    }*/
    
    /**
     * 栏位商品列表
     */
    @Override
	public PageInfo<ProductDto> columnProdList(ColumnProdDTO dto) {
    	PageHelper.startPage(dto.getCurrentPage(), dto.getPageSize());
        //栏位id
        if(!StringUtil.isBlank(dto.getColumnId())){
        	List<ProductDto> list = columnProdDao.selectByColumuId(dto.getColumnId());
        	//过滤未上架的商品
            if(list!= null && list.size() > 0){
                StringBuilder prodIds = new StringBuilder();
                Date imgDate = new Date();
                for(ProductDto productDto : list){
                    prodIds.append(productDto.getProdId()).append(",");
                    productDto.setAdImg(AliOSSUtil.getFileUrl(productDto.getAdImg(), AliOSSUtil.getNoEffictDateByDay(1)));
                }
                if(prodIds.length() > 0){
                    prodIds = prodIds.delete(prodIds.length() -1,prodIds.length());
                    List<ProductStatusDTO> statusList = productStatusDao.findStatusByProdIds(prodIds.toString());
                    if(statusList != null && statusList.size() > 0){
                        Iterator<ProductDto> iterator = list.iterator();
                        while (iterator.hasNext()){
                            ProductDto product = iterator.next();
                            for(ProductStatusDTO productStatus :statusList){
                                if(product.getProdId().equals(productStatus.getProdId())){
                                    if(!productStatus.getProdStatus().equals(1)){
                                        iterator.remove();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        	
        	PageInfo<ProductDto> page = new PageInfo<>(list);
        	return page;
        }
        return null;
	}

    /**
     * 栏位商品列表获取,存Redis
     */
	@Override
	public String columnProdListFromRedis(ColumnProdDTO dto) {
		Integer currentPage = dto.getCurrentPage();
		Integer pageSize = dto.getPageSize();
        String redisKey = RedisKeyEnum.APP_HOME_PAGE_COLUMN_PRODUCT_LIST.getKey() + "columnId_" + dto.getColumnId() + "_page_" + currentPage;
        //从redis获取数据
        String columns = getcolumnProdListFromRedis(redisKey);
        if(!StringUtil.isBlank(columns)){
        	logger.info("从redis获取数据");
            return columns;
        }
        //从mysql获取首页数据
        synchronized (this){
            columns = getcolumnProdListFromRedis(redisKey);
            if(StringUtil.isBlank(columns)){
                columns = getColumnProdListFromMysql(redisKey,dto);
            }
        }
        logger.info("从mysql获取首页数据");
        return columns;
	}

	private String getColumnProdListFromMysql(String redisKey,ColumnProdDTO dto) {
        String result = "";
        Response response = new Response();
        
        PageInfo<ProductDto> pageList = columnProdList(dto);
        
        response.setRes_data(pageList);
        response.setResponseCode(ResponseCodeEnum.SUCCESSED);
        result = JsonUtil.toJson(response);
        try {
            redisService.set(redisKey,result,2L,TimeUnit.MINUTES);
        }catch (Exception e){
            logger.error("===>redis保存数据异常");
        }
        return result;
	}

	private String getcolumnProdListFromRedis(String redisKey) {
		//从redis获取栏位商品数据
        String result = "";
        try{
            result = redisService.get(redisKey);
        }catch (Exception e){
            logger.error("===>从redis获取数据异常");
        }
        return result;
	}

	private Integer getPageId(){
        Integer pageId = null;
        try{
            pageId = Integer.parseInt(jmConfigService.getValueByKey("current_effective_pageId"));
        }catch (Exception e){
            logger.error("===>pageId转换异常");
        }
        if(pageId == null){
            pageId = 1;
            logger.error("===>没有读取到pageId，所以使用默认值1");
        }
        return pageId;
    }
}
